import React, { Component } from "react";
import "styles/home/helios-service-charts.scss";
import { eventTrack, messages } from "share/common";
import { Button, DatePicker, Spin, Popover } from "antd";
import menuRoute from "routes/menuRoute";
import moment from "moment";
import Chart from "components/echarts";
import ChartService from "containers/home/home-comp/charts-service";
import homeService from "containers/home/home.service";
import debounce from "lodash.debounce";
import TweenOne from "rc-tween-one";
import ExampleTag from "containers/home/home-dashboard-share/example-tag";
import WaterMark from "components/water-mark";
import Condition from "components/condition";
import NullCard from "containers/dashboard/dashboard-component/null-card";

const { MonthPicker } = DatePicker;
const { If, Else } = Condition;

const typeMap = {
  OCR: {
    openKey: "openServiceOCRFlag",
    title: messages("basic-1.key1") /*拍照识别*/,
    description: messages("basic-1.key2") /*通过拍照，系统自动识别出发票信息填入单据*/,
  },
  CHECK_INVOICE: {
    openKey: "openServiceCheckInvoiceFlag",
    title: messages("basic-1.key3") /*发票查验*/,
    description: messages("basic-1.key4") /*扫描发票二维码，获取来自国家税务局的发票核对结果*/,
  },
  BWE: {
    openKey: "openServiceBWEFlag",
    title: messages("basic-1.key5") /*银企直联*/,
    description: messages("basic-1.key6") /*对接银行系统，便捷管理银行账户、转账支付等*/,
  },
};

class HeliosServiceCharts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: moment(new Date()),
      dataOpen: false,
      loading: true,
      option: {},
      currentData: undefined,
      animation: null,
    };
    this.flag = false;
    this.cardFlag = false;
    this.handleOtherOption = debounce(this.handleOtherOption, 500);
  }

  onOk = (e) => {
    this.setState({ time: e, loading: true }, () => {
      this.handleOtherOption(this.props, true);
    });
    eventTrack({
      category: "1218-新首页-埋点",
      action: `用户使用了【${typeMap[this.props.type].title}】的日期选择器，选择了${moment(e).format("YYYY-MM")}`,
      label: this.props.tenant.tenantName,
    });
  };

  disabledDate = (current) => {
    return current && current > moment().endOf("year");
  };

  componentWillReceiveProps(nextProps) {
    this.checkStatus(nextProps);
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
    this.checkStatus(this.props);
  }

  checkStatus = (props) => {
    this.check1(props);
    this.check2(props);
  };

  check1 = (props) => {
    if (this.flag) return;
    if (props.openData) {
      this.flag = true;
      this.setState({ dataOpen: props.openData[typeMap[props.type].openKey] }, () => {
        this.handleOption(props, true);
      });
    }
  };

  check2 = (props) => {
    const { trialTenant, cardData, type } = props;
    if (this.cardFlag) return;
    if (cardData && JSON.stringify(cardData) !== "{}") {
      this.cardFlag = true;
      if (type === "BWE" || trialTenant) {
        this.handleOption(props);
      } else {
        this.trigger(type === "CHECK_INVOICE" ? cardData.checkInvoiceRemainQty : cardData.ocrRemainQty);
      }
    }
  };

  setLoading = () => {
    this.setState({ loading: true });
  };

  getRealData = () => {
    const { cardData } = this.props;
    if (this.state.dataOpen) {
      this.handleOption(this.props, true);
    } else if (JSON.stringify(cardData) !== "{}") {
      this.handleOption(this.props, true);
    }
  };

  handleOption = (props, forceUpdate = false) => {
    const { type, cardData, trialTenant, openData } = props;
    if (type === "BWE" && cardData.totalCount) {
      const option = ChartService.createOptions({
        type: "pie",
        data: {
          canUse: trialTenant ? 2 : cardData.bweAvailableQty || 0,
          used: trialTenant ? 12 : cardData.bweAvailableMonthlyQty || 0,
        },
      });
      this.setState({ option, loading: !(JSON.stringify(openData) !== "{}" || trialTenant) });
    } else {
      this.trigger(type === "CHECK_INVOICE" ? cardData.checkInvoiceRemainQty : cardData.ocrRemainQty);
      this.handleOtherOption(props, forceUpdate);
    }
  };

  handleOtherOption = (props, forceUpdate = false) => {
    const { type, trialTenant } = props;
    const { time, currentData, OCRData } = this.state;
    if (type === "CHECK_INVOICE") {
      if (!forceUpdate && currentData) return;
      homeService
        .getCheckInvoiceData({ yearMonthFilter: moment(time).format("YYYY-MM") }, trialTenant)
        .then((res) => {
          if (res && res.status === 200) {
            const option = ChartService.createOptions({
              type: "line",
              data: res.data.chkInvUsedMthlyQtyStatistics,
              config: {
                color: ["#4B8DFF"],
                barColor: [
                  { offset: 0, color: "rgba(31,112,252,0.30)" },
                  { offset: 1, color: "rgba(75,141,255,0.00)" },
                ],
                name: typeMap[type].title,
              },
            });
            this.setState({ currentData: res.data, option, loading: false });
          }
        })
        .catch(() => {
          this.setState({ loading: false });
        });
    } else if (type === "OCR") {
      if (!forceUpdate && currentData) return;
      homeService
        .getOCRData({ yearMonthFilter: moment(time).format("YYYY-MM") }, trialTenant)
        .then((res) => {
          if (res.status === 200) {
            const option = ChartService.createOptions({
              type: "line",
              data: res.data.ocrUsedMthlyQtyStatistics,
              config: {
                color: ["#1CAEFF"],
                barColor: [
                  { offset: 0, color: "rgba(136,225,255,0.30)" },
                  { offset: 1, color: "rgba(80,192,255,0.00)" },
                ],
                name: typeMap[type].title,
              },
            });
            this.setState({ currentData: res.data, option, loading: false });
          }
        })
        .catch(() => {
          this.setState({ loading: false });
        });
    }
  };

  trigger = (value) => {
    this.setState({
      animation: {
        Children: {
          value: typeof value === "number" ? value : 0,
          floatLength: 0,
          formatMoney: true,
        },
        duration: 1000,
      },
    });
  };

  goOrderManagement = (key) => {
    const url = menuRoute.getPageUrlByKey("order-management").replace(":orderType", key);
    this.context.router.push(url);
    eventTrack({
      category: "1218-新首页-埋点",
      action: `【${typeMap[key].title}】，点击了[查看购买]`,
      label: this.props.tenant.tenantName,
    });
  };

  render() {
    const { option, loading, dataOpen } = this.state;
    const { type = "OCR", trialTenant = false, onConfirm, isDingTalkEnv } = this.props;
    return (
      <div id={`helios-service-charts-guide-id-${type}`} className={"helios-service-charts one-third-content"}>
        <div className="head-wrapper">
          <div className="home-title">{typeMap[type].title}</div>
          {dataOpen && !trialTenant && (
            <div className="buy-service">
              <Button onClick={() => this.goOrderManagement(type)}>{messages("basic-1.key26") /*查看订单*/}</Button>
            </div>
          )}
        </div>
        <Condition>
          <If value={dataOpen || trialTenant || loading}>
            <div className="introduce">{typeMap[type].description}</div>
            {type !== "BWE" && (
              <div className="calendar-and-remain">
                <Popover
                  trigger={trialTenant ? "hover" : ""}
                  content={trialTenant ? messages("basic-1.key242") /*示例数据不支持选择月份*/ : ""}
                >
                  <span>
                    <MonthPicker
                      disabled={trialTenant || loading}
                      disabledDate={(current) => current && current.valueOf() > Date.now()}
                      allowClear={false}
                      style={{ width: 102 }}
                      onChange={this.onOk}
                      value={this.state.time}
                      defaultValue={moment()}
                    />
                  </span>
                </Popover>
                {!trialTenant && (
                  <div className="remain-box">
                    {messages("basic-1.key243") /*可用余量：*/}
                    <TweenOne animation={this.state.animation} className="number-box">
                      -
                    </TweenOne>
                    <div className="update-time">{messages("basic-1.key244") /*每日00:00:00更新*/}</div>
                  </div>
                )}
              </div>
            )}
            <div>
              <Spin spinning={loading}>
                {!trialTenant && <WaterMark />}
                <Chart options={option} height={type === "BWE" ? 200 : 158} />
              </Spin>
            </div>
          </If>
          <Else>
            <NullCard
              top={20}
              imgType={type}
              message={typeMap[type].description}
              onClick={() => this.goOrderManagement(type)}
              btnMessage={
                isDingTalkEnv && sessionStorage.getItem("isDingTalkSSO") === "true"
                  ? ""
                  : messages("basic-1.key296") /*查看购买*/
              }
            />
          </Else>
        </Condition>
        <ExampleTag show={trialTenant} onConfirm={onConfirm} />
      </div>
    );
  }
}

HeliosServiceCharts.propTypes = {};

HeliosServiceCharts.contextTypes = {
  router: React.PropTypes.object,
};

export default HeliosServiceCharts;
